<template>
  <view>
    <view class="btn" style="left: 200rpx;top: 500rpx;" @click="onBtnVideoChat">音视频通话</view>
    
    <audio
      id="audio" 
      autoplay
      playsinline
      style="width: 0; height: 0;"
    />
  </view>
</template>

<script>
  import WebRTCSDK from '../../static/js/WebRTCSDK.js'
  var sdk      = null 
  var deviceId = 'device_xxx' // 设备id 
  var roomId   = 300 
  var callWait = false
  var inCall   = false 
  
  export default {
    onLoad() {
      this.initWebRtc()
    },
    methods: {
      initWebRtc() {
        if (!sdk) {
          console.log('=== initWebRtc')
          
          // 创建 SDK 实例
          sdk = new WebRTCSDK({
            // signalingServer: 'wss://47.101.40.207:8299',
            debug: true,
            autoReconnect:true
          })
          
          // 连接信令服务器
          sdk.connect({
            cus_channel: '贵阳捷逸4S店一体机',
            cus_node: '补充流水'
          }, deviceId, roomId) 
          
          // 事件监听
          sdk.on('connected', () => {
            console.log('已连接到信令服务器')
          })
          sdk.on('disconnected', () => {
            console.log('与信令服务器断开连接')
          })
          sdk.on('peerJoined', (uid) => {
            console.log(`用户 ${uid} 加入`)
          })
          sdk.on('peerLeft', (uid) => {
            console.log(`用户 ${uid} 离开`)
          })
          sdk.on('callWait', () => {
            callWait = true
            setTimeout(() => { 
              if (callWait && !inCall) {
                sdk.endCall()
                console.log('无人接听')
                console.log(sdk)
              }
            }, 15000)
            console.log('等待通话接听')
          })
          // 通话事件
          sdk.on('callStarted', () => {
            callWait = false
            inCall = true
            console.log('通话已开始')
          })
          sdk.on('callEnded', () => {
            callWait = false
            inCall = false
            console.log('通话已结束')
          })
          sdk.on('error', ({ type, error }) => {
            console.error(`错误 [${type}]:`, error)
            if (type === 'offline') {
              console.log('对方不在线')
              sdk.endCall()
            }
          }) 
        }
      },
      
      onBtnVideoChat() {
        // 开始通话
        sdk.startCall({ 
          order_id: 'xxx', // 订单号
          name: 'xxx', // 姓名，
          amount: 'xxx' // 融资额
        })

      },
    }
  }
</script>

<style scoped>
.btn {
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #00aaff;
    color: #fff;
    
    position: absolute;
    left: 200rpx;
    top: 1000rpx;
  }
</style>